package com.qfedu.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import io.swagger.annotations.Api;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

/**
 * @version 1.0
 * @Author:Raoult
 * 做难事必有所得
 */
@RequestMapping("/pay")
@Controller
@Api(tags = "支付接口")
public class PayController {

        private static final String privateKey="MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCVYh6Vo5KMiRTNzQPYmU6umEelzP8HV0Jzp5/tj562y76aiVhw7Jd2dj3osOLtVqQgWUvFZZwchRB59OYwKRW/IdJQT0NKzQK/naxDCE9BfHUSbdNUInBqSRZgzTnqU1X+s2GgIC365ZxbTlkBdJKVSjz7MBmlN0pJLvHjhWc5So8WKW8x9QhjztAXdRFkU3IOhqQNYnhLMTm8ofTI32Hs1qHrXwDYcjLSihEskMA4tqgVyLs0NnVXh65xvVDP5EoG13vqzBZxENQ6V0TANxK6H00X6AeaBRDvEsFDcUgjymz+nOReYAVuXS9c7Re/Z7MlSsBXEwbi2C2HS1f3FELhAgMBAAECggEAPefOkuaZecHpLCw01tMZh0M2FeCxI0KnGDS0Ewe8lzYyA+q9CvcRAZeYqlB7ii2okHtQ6jnkivEd1dyGdBjimTWT6ZIfaeUxqWTXGWRdK98+yOdYd3paKcGmE3GY+aGVdpqx72DGjT4QIMqEGhVMFbARO2tAhXY3Q8K/nTEQiO3ZswHIJ/dgJkfIC0NY6b3XdSWJ3y7gQpDl6Q36+4/CkjhmN2yUs9A3oWenH5i9VoTpA94DRbuMDu1CM+1IKkVXNyeaq2r983h6bRDan8MP0/HumTxZZB9f8nB8UMiqmiwxp8/tDFxd6+f/p1EEwFkB2PPwrpQjLl0LhCax3regTQKBgQDOYCvQFSq2iBtgdVWFvUwvyRM8iRUg3djK2vQMxlxXGc+HG2urzaIFG9d/VodITWri6ddvT99sthm7WzTDbr+EWcVZpMTwdju/KUd/TA+tD2zk+cUHfwau/jJCWBg8WsZwTomvMnYKUYN7EDycSdeaRdTtvLOAwuX6Yd3HnGLXawKBgQC5Ta2o0taqrEeNgPfoWybORBWFgOIDYYiASEg1iIhlHawcmHFgB3onKCCEx1yueWZMnZTy6cVis2ILGB8wGEaupzWnEQKQWPmUpF46Am63ySn166RsK3aLUpxblC02LOK73YWG96lysouHiFvfxFjxptv5snLjG3d0th/FaMB94wKBgQDCFcvee6mZ1FL62h4+EpLN9epzafBG4px52oTeZsZ827dCNtWB03fmGhMGnJfJtZUqJgUHmDRlBrUYcGQkz8ipbcudzMmx41+5HdcxrpSnivQ8O3HC5QGiHUmi/zp7uFsbT6FI9MnyVkqyt8hoq0FqwvXHR0oBdEnYuaVbjoWeVQKBgCwsZ1SShlgDX79M2kxKxnJvao37zmUt8ANct9IDLTilnSzn7kcNIUKKX04n1GFHUWq8OhC6R7KivqGUa4Lklpz2AWVFOc49V6nmkQvVHp2zV8xnEzgyGD1YQSvXo/uBMb/FLBqjmYJdK8Pwbq5mOSnKNDBPKPIYzx5EeEhwE0svAoGAMzdyI2BglxIwq4cKJUITm1mvNdLQ2D+sfEVGYnie5kOGUxEzXe0Jnq5C6BWzIPM0LDyC8l+h6ywl5v6VKtEHXuNWasYjSGgvjAikMipWb76EX+P3f6s/x9J0tfNM9gzSUnn0OgAddiOCt2zXSAakoZKw5L8gpeS1jtJhqwPre0c=";
        private static final String alipaypubicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlWIelaOSjIkUzc0D2JlOrphHpcz/B1dCc6ef7Y+etsu+molYcOyXdnY96LDi7VakIFlLxWWcHIUQefTmMCkVvyHSUE9DSs0Cv52sQwhPQXx1Em3TVCJwakkWYM056lNV/rNhoCAt+uWcW05ZAXSSlUo8+zAZpTdKSS7x44VnOUqPFilvMfUIY87QF3URZFNyDoakDWJ4SzE5vKH0yN9h7Nah618A2HIy0ooRLJDAOLaoFci7NDZ1V4eucb1Qz+RKBtd76swWcRDUOldEwDcSuh9NF+gHmgUQ7xLBQ3FII8ps/pzkXmAFbl0vXO0Xv2ezJUrAVxMG4tgth0tX9xRC4QIDAQAB";
        @RequestMapping("/alipay")
        public void pay( HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
                //1.生成支付宝请求客户端 1.serverURL 代表 请求的支付宝网关地址 2.appid 商户的标识 3.应用私钥。4.格式转换 默认时Json .5. 编码格式 默认是 utf-8 6.支付宝公钥。7.加密方式默认是 RSA2
                AlipayClient alipayClient =  new DefaultAlipayClient( "https://openapi.alipaydev.com/gateway.do" , "2021000121673948", privateKey, "json", "utf-8", alipaypubicKey, "RSA2");  //获得初始化的AlipayClient
                //2.声明交易方式，网页端支付
                AlipayTradePagePayRequest alipayRequest =  new  AlipayTradePagePayRequest(); //创建API对应的request
                //3.returnurl 支付宝同步返回的参数页面
                alipayRequest.setReturnUrl( "http://localhost:8081/#/success" );
                //4.NotifyUrl 支付宝的异步通知
                alipayRequest.setNotifyUrl( "http://331t2j2729.zicp.vip/pay/notifyUrl" ); //在公共参数中设置回跳和通知地址
                //5.设置支付的参数 out_trade_no 订单号必须保持唯一 product_code 固定为 FAST_INSTANT_TRADE_PAY total_amount 价格，subject 主题 body 内容
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("out_trade_no", UUID.randomUUID().toString());
                jsonObject.put("product_code", "FAST_INSTANT_TRADE_PAY");
                jsonObject.put("total_amount", "888888");
                jsonObject.put("subject", "包子");
                jsonObject.put("body", "包子是金子馅");
                //入库，设置支付状态为未支付状态

                alipayRequest.setBizContent(jsonObject.toJSONString()); //填充业务参数
                String form= "" ;
                try  {
                        //请求支付宝 获取到支付表单 form表单
                        form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
                }  catch  (AlipayApiException e) {
                        e.printStackTrace();
                }
                httpResponse.setContentType( "text/html;charset=utf-8");
                httpResponse.getWriter().write(form); //直接将完整的表单html输出到页面
                httpResponse.getWriter().flush();
                httpResponse.getWriter().close();
        }

        @RequestMapping("/notifyUrl")
        public void notfiyUrl(HttpServletRequest request) throws AlipayApiException {
                //将异步通知中收到的所有参数都存放到map中 将Request请求中的参数重组为map集合
                Map<String, String> paramsMap = convertRequestParamsToMap(request);

                boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap, alipaypubicKey, "utf-8", "RSA2"); //调用SDK验证签名
                if(signVerified){
                        // TODO 验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
                        System.out.println("验签成功！！！");
                        System.out.println("当前回调的订单编号为:"+paramsMap.get("out_trade_no"));
                        System.out.println("当前回调的appid为:"+paramsMap.get("app_id"));
                        System.out.println("当前订单支付的金额为:"+paramsMap.get("total_amount"));
                        System.out.println("当前订单状态为:"+paramsMap.get("trade_status"));
                        //通过订单号更改数据库的该笔订单的交易状态

                }else{
                        // TODO 验签失败则记录异常日志，并在response中返回failure.
                }
        }

        // 将request中的参数转换成Map
        private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
                Map<String, String> retMap = new HashMap<String, String>();

                Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

                for (Map.Entry<String, String[]> entry : entrySet) {
                        String name = entry.getKey();
                        String[] values = entry.getValue();
                        int valLen = values.length;

                        if (valLen == 1) {
                                retMap.put(name, values[0]);
                        } else if (valLen > 1) {
                                StringBuilder sb = new StringBuilder();
                                for (String val : values) {
                                        sb.append(",").append(val);
                                }
                                retMap.put(name, sb.toString().substring(1));
                        } else {
                                retMap.put(name, "");
                        }
                }

                return retMap;
        }


}






